package com.xs.lomo;

import java.util.ArrayList;
import java.util.Collection;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.RosterGroup;
import org.jivesoftware.smack.RosterListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Presence;

import com.xs.customdialog.CustomDialog;
import com.xs.listview.RosterItem;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;

@SuppressLint({ "UseSparseArrays", "HandlerLeak" })
public class BuddyActivity extends Activity implements 
							OnChildClickListener, 
							OnGroupClickListener{
	private static final int BACKKEY_DIALOG = 1;
	private Roster rosterCtx = null;
	private ListViewAdapter adapter = null;
	private ExpandableListView listView = null;
	private XMPPConnection g_xsConnCtx = null;
	
	private ProgressDialog proDialog;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);  
		setContentView(R.layout.roster); 
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.buddylabel);
		
		listView = (ExpandableListView)findViewById(R.id.listView);
		listView.setOnChildClickListener(this);
		listView.setOnGroupClickListener(this);
		listView.setGroupIndicator(null);
		
		adapter = new ListViewAdapter(this, new ArrayList<String>(),
                					new ArrayList<ArrayList<RosterItem>>());
		
		listView.setAdapter(adapter);
		g_xsConnCtx = new LomoCtx().getXmppCtx();
		
		CreateBuddyView();
		ListerPresence();
	}
	
	private void CreateBuddyView(){
		rosterCtx = g_xsConnCtx.getRoster();
		for(RosterGroup g : rosterCtx.getGroups()) {	
			Log.d("Roster","Group ->"+g.getName());
			for(RosterEntry entry : g.getEntries()) {
				RosterItem buddy = new RosterItem(null);
				String buddyState = null,
					   buddyName = null;
				
				Presence presence = rosterCtx.getPresence(entry.getUser());  
				buddyState = presence.getStatus();
				buddyName = entry.getName();
				if(null == buddyName){
					buddyName = entry.getUser().substring(0, entry.getUser().indexOf("@"));
				}
				
				buddy.setGroup(g.getName());
				buddy.setName(buddyName);
				if(true == presence.isAvailable()){
					if(null != buddyState){
						buddy.setState(buddyState);
					}else{
						buddy.setState(getString(R.string.online_state));
					}					
					buddy.setImageState(true);
				}else{
					buddy.setState(getString(R.string.offline_state));
					buddy.setImageState(false);
				}
				adapter.addItem(buddy);
				LoadItemHandler.sendEmptyMessage(1);				
			}
    	}
	}
	
	public void ListerPresence(){
		if(null != rosterCtx){
			rosterCtx.addRosterListener(new RosterListener() {		
				@Override
				public void presenceChanged(Presence pre) {
					String name = null, buddyState = null;
					RosterItem buddy = null;
					Intent StateIntent = new Intent();

					name = pre.getFrom().substring(0, pre.getFrom().indexOf("@"));
					buddyState = pre.getStatus();
					
					buddy = (RosterItem)adapter.getChildItemByName(name);
					if(null == buddy){
						return;
					}
					StateIntent.setAction("lomo.action.state");
					StateIntent.putExtra("BuddyName", name);
					if(false == pre.isAvailable()){
						buddy.setImageState(false);
						int iPos = 0;
						String LastStat = buddy.getState();
						String NewStat = null;
						iPos = LastStat.indexOf("|");
						if(0 < iPos){
							LastStat = LastStat.substring(iPos);
							NewStat = getString(R.string.offline_state)+LastStat;
						}else{
							NewStat = getString(R.string.offline_state);
						}
						buddy.setState(NewStat);
						LoadItemHandler.sendEmptyMessage(1);
						StateIntent.putExtra("BuddyState", getString(R.string.offline_state));
						
					}else{
						if(null != buddyState){
							buddy.setState(buddyState);
							StateIntent.putExtra("BuddyState", buddyState);
						}else{
							buddy.setState(getString(R.string.online_state));
							StateIntent.putExtra("BuddyState", getString(R.string.online_state));
						}						
						buddy.setImageState(true);
						LoadItemHandler.sendEmptyMessage(1);
					}
					BuddyActivity.this.sendBroadcast(StateIntent);
					Log.d("BuddyActivity","presenceChanged"); 
				}

				@Override
				public void entriesUpdated(Collection<String> arg0) {
					Log.d("BuddyActivity","entriesUpdated");  
				}

				@Override
				public void entriesDeleted(Collection<String> arg0) {
					Log.d("BuddyActivity","entriesDeleted");  
				}
	
				@Override
				public void entriesAdded(Collection<String> arg0) {
					Log.d("BuddyActivity","entriesAdded");  
				}
			});
		}
	}
	@Override
	public boolean onChildClick(ExpandableListView parent, View v,
			int groupPosition, int childPosition, long id) {
		RosterItem child = (RosterItem)adapter.getChild(groupPosition, childPosition);
		Intent CtxActIntent =new Intent();
		Bundle bundle = new Bundle();
		
		bundle.putString("BuddyName", child.getName());
		bundle.putString("BuddyState", child.getState());
		CtxActIntent.setClass(BuddyActivity.this, FuncActivity.class);
		CtxActIntent.putExtras(bundle);
		startActivity(CtxActIntent);
		
//		Toast.makeText(getBaseContext(), child.getName()+"is clicked "+child.getState(), Toast.LENGTH_SHORT).show();
		return false;
	}
	
	@Override
	public boolean onGroupClick(ExpandableListView parent, View v,
			int groupPosition, long id) {
//		Toast.makeText(getBaseContext(), "Group clicked", Toast.LENGTH_SHORT).show();
		return false;
	}

	private Handler LoadItemHandler = new Handler(){
		@Override
        public void handleMessage(Message msg){
			adapter.notifyDataSetChanged();
            super.handleMessage(msg);
        }
	};
	@Override  
    public boolean onKeyDown(int keyCode, KeyEvent event)  
    {  
        if (keyCode == KeyEvent.KEYCODE_BACK )  {
        	BuddyActivity.this.showDialog(BACKKEY_DIALOG);
        }        
        return false;  
          
    } 
	
	public Dialog onCreateDialog(int dialogId){
		Dialog dialog = null;
    	switch (dialogId) {
	    	case BACKKEY_DIALOG:
				CustomDialog.Builder customBuilder = new CustomDialog.Builder(BuddyActivity.this);
				customBuilder.setTitle(getString(R.string.note))
					.setMessage(getString(R.string.exit_desc_note))
					.setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							BuddyActivity.this.dismissDialog(BACKKEY_DIALOG);
						}
					})
					.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							g_xsConnCtx.disconnect();
							BuddyActivity.this.finish();
						}
					});
	            dialog = customBuilder.create();
	    		break;
    	}
    	return dialog;	
	}
    
	protected void onDestroy(){
		System.exit(0);
		super.onDestroy();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.buddymenu, menu);
		return super.onCreateOptionsMenu(menu); 
	}
	
	public boolean onOptionsItemSelected(MenuItem item){
		int itemID = item.getItemId();
		switch(itemID){
		case R.id.buddy_refresh:
			final IQ GetRosterIQ = new IQ(){
				@Override
				public String getChildElementXML() {
					//<iq id="kJKvH-2" type="get"><query xmlns="jabber:iq:roster" ></query></iq>
					String sb = "<query xmlns=\"jabber:iq:roster\"></query>";
					return sb;
				}		
			};
			GetRosterIQ.setType(IQ.Type.GET);
			g_xsConnCtx.sendPacket(GetRosterIQ);
			adapter.clearItem();
			
			proDialog = ProgressDialog.show(this, getString(R.string.refresh_note), getString(R.string.refreshing_note), true, true);
			CreateBuddyView();
			proDialog.dismiss();
			break;
		}
		return true;
	}
}